from absFiles.BaseWidget import *
from tablewidgets.MyShowTableButton import *
from tablewidgets.MyTableWidget import *
from PlayCore.MyMediaList import *
from middleWidgets.MiddleStackWidget import *
from myDatabase import MyDataBase

from PyQt5 import QtCore,QtWidgets,QtGui,QtMultimedia
from PyQt5.QtCore import QObject,QDir,QMimeData,QUrl,QEventLoop,QFileInfo,QTime
from PyQt5.QtGui import QColor,QWheelEvent,QDragEnterEvent
from PyQt5.QtMultimedia import QMediaPlayer
from PyQt5.QtWidgets import QFileDialog,QVBoxLayout,QMessageBox,QTableWidget,QTableWidgetItem

BGcolor=QColor(230,230,230)
class MyTablePlayListFinal(BaseWidget):
    _instance = None
    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(MyTablePlayListFinal, cls).__new__(cls,*args,**kwargs)
        return cls._instance
    def __init__(self,parent=None):
        super(MyTablePlayListFinal, self).__init__(parent)
        self.PlayListName = "新建列表"
        self.Btntable = MyShowTableButton()
        self.table = MyTableWidget()
        self.PlayList = MyMediaList()
        self.midleft0 = None

        self.table.setTableFinal(self)
        self.Btntable.setTableFinal(self)
        self.PlayList.setTableFinal(self)

        self.setMouseTracking(True)
        self.setAcceptDrops(True)

        self.Btntable.sig_emptyList.connect(self.slot_emptyList)
        self.Btntable.sig_addSong.connect(self.slot_addSong)
        self.table.sig_RowCountChange.connect(self.Btntable.slot_updateSongCount)
        self.Btntable.clicked.connect(self.slot_showHideTable)
        self.table.sig_delIndex.connect(self.PlayList.slot_removeSong)
        self.table.sig_addSong.connect(self.slot_addSong)
        self.table.sig_addSongFolder.connect(self.slot_addSongFolder)

        vlayout = QVBoxLayout()
        self.setMinimumSize(310,40)
        self.setMaximumWidth(380)

        vlayout.addWidget(self.Btntable)
        vlayout.addWidget(self.table)
        vlayout.setContentsMargins(0,0,0,0)
        vlayout.setSpacing(0)
        self.setLayout(vlayout)

    def addToPlayList(self,name,url,dur,strHash,bAddtoDB):
        rowcount = self.table.rowCount()
        self.table.insertRow(rowcount)
        self.table.setItem(rowcount,0,QTableWidgetItem(""))
        self.table.setItem(rowcount,1,QTableWidgetItem(name))
        self.table.setItem(rowcount,2,QTableWidgetItem(dur + "      "))
        self.table.item(rowcount,2).setTextAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)


        self.PlayList.addPlayList(url,strHash)
        if bAddtoDB:
            MyDataBase.addSong(self.ShowButtonName(),name,url,dur,strHash)

    def getCurrentList(self):
        return MyTablePlayListFinal._instance
    def wheelEvent(self, e : QWheelEvent):
        i = e.pixelDelta()/5.0
        value = self.midleft0.verticalScrollBar().value()
        self.midleft0.verticalScrollBar().setValue(value - i)
    def paintEvent(self, e: QtGui.QPaintEvent):
        super(MyTablePlayListFinal, self).paintEvent(e)
        p = QPainter(self)
        p.setPen(BGcolor)
        p.drawLine(0,self.height()-1,self.width()-1,self.height()-1)

    def dragEnterEvent(self, e:QtGui.QDragEnterEvent):
        if e.mimeData().hasFormat("test/uri-list"):
            e.acceptProposedAction()

    def dropEvent(self, e:QtGui.QDropEvent):
        files = e.mimeData().urls()
        player = QMediaPlayer()
        lp = QEventLoop()
        for file in files:
            if file.toString().find(".mp3"):
                info = file.toLocalFile()
                name = info.completeBaseName()
                if self.PlayList.GetList().count(file.toString()) < 1:
                    filePath = file.toLocalFile()
                    player.setMedia(QUrl(filePath))
                    timer = QTimer()
                    timer.timeout.connect(lp.quit)
                    timer.setSingleShot(True)
                    timer.start(2000)

                    player.durationChanged.connect(lp.quit)
                    lp.exec()
                    musicTime = player.duration()
                    total_time = QTime(0,(musicTime/60000)%6,(musicTime/1000)%60)
                    duration = total_time.toString("mm:ss")

                    self.addToPlayList(name,file.toLocalFile(),duration)
                    self.setAutoLayout()

    def slot_emptyList(self):
        count = self.table.rowCount()
        mb = QMessageBox.warning(None,"warning","确定要清空？",QMessageBox.Ok|QMessageBox.Cancel)

        if(mb == QMessageBox.Cancel)
            return
        MyDataBase.emptyList(self.ShowButtonName())

        if self == MyTablePlayListFinal.getCurrentList():
            self.stopCurrentSong()
        for i in range(count):
            row = self.table.rowCount() - 1
            self.table.slot_cellEnter(-1,0)
            self.table.sig_delIndex.emit(row)
            self.table.removeRow(row)
            i+=1

        self.PlayList.clearMediaList()
        self.setAutoLayout()

    def setAutoLayout(self):
        self.table.setAutoLayoutSize()

    def updateBGcolor(self):
        BGcolor = MiddleWidgetLeft.color
        self.update()

    def setCurrentSongAlbumPic(self,strPath):
        self.table.PlayingWid.btnLab.setIcon(QPixmap(strPath).scaled(52,52))

    def currentSongDuration(self):
        index = self.table.currentSongIndex()
        it = self.table.item(index,2)
        if it != None:
            text = it.text()
            if len(text) == 0:
                self.table.getHoverDuration().simplified()
            else:
                text.simplified()
        else:
            self.table.getHoverDuration().simplified()

    def currentSongDurationToInt(self):
        time = QTime.fromString(self.currentSongDuration(),"mm:ss")
        return time.minute()*60*1000+time.second()*1000

    def stopCurrentSong(self):
        MainWindow.GetInstance().player().pause()
        MainWindow.GetInstance().player().setMedia(None)
        self.table.PlayingWid.setCurrentSongItem(None)
        self.midleft0.setOriginalStatus()


    def updateConvientButon(self):
        pass

    def slot_shoHideTable(self):
        if self.table.isHidden():
            self.table.hide()
            for f in self.MidLef0.myTablePlayListFinalVector():
                f.table.hide()
            self.midleft0.convientShowTableBtn().hide()

        else:
            self.table.show()
            for f in self.midleft0.myTablePlayListFinalVector():
                if f != self:
                    f.table.hide()

    def getlistfromDataBase(self):
        MyDataBase.readListSongInfo(self, self.ShowButtonName());
        self.Btntable.slot_updateSongCount();

    def slot_addSong(self):
        initialDir = "F:/"
        files = QFileDialog.getOpenFileNames(self,"选择文件",initialDir,"*.mp3")
        if len(files) < 1:
            return

        player = QMediaPlayer()
        lp = QEventLoop()
        for file in files:
            info = QFileInfo(file)
            name = info.completeBaseName()
            if self.PlayList.GetList().count(file) < 1:
                player.setMedia(QUrl(file))
                timer = QTimer()
                timer.timeout.connect(lp.quit)
                timer.setSingleShot(True)
                timer.start(2000)

                player.durationChanged.connect(lp.quit)
                lp.exec()

                musicTime = player.duration()
                total_time= QTime(0,(musicTime/60000)%6,(musicTime/1000)%60)
                duration = total_time.toString("mm:ss")

                self.addToPlayList(name,file,duration)
                self.setAutoLayout()

    def slot_addSongFolder(self):
        dir = QFileDialog.getExistingDirectory(self,"打开本地歌曲文件夹","/home",QFileDialog.ShowDirsOnly|QFileDialog.DontResolveSymlinks)

        dir = QDir(dir)
        if not dir.exists():
            return
        dir.setFilter(QDir.Files|QDir.NoSymLinks)
        list = dir.entryInfoList()
        file_count = len(list)

        if file_count <= 0:
            return
        files = []
        for file in list:
            suffix = file.suffix().lower()
            if suffix == "mp3":
                absolute_file_path = file.absoluteFilePath()
                files.append(absolute_file_path)

        if(len(files)<=0)
            return
        player = QMediaPlayer()
        lp = QEventLoop()
        for file in files:
            info = QFileInfo(file)
            name = info.completeBaseName()
            if self.PlayList.GetList().count(file) <= 0:
                filePath = file
                player.setMedia(QUrl(filePath))
                player.durationChanged.connect(lp.quit)
                lp.exec()
                musicTime = player.duration()
                total_time = QTime(0, (musicTime / 60000) % 6, (musicTime / 1000) % 60)
                duration = total_time.toString("mm:ss")

                self.addToPlayList(name, file, duration)
                self.setAutoLayout()


    def slot_addSongFromSearchTable(self,namelist,urllist,durlist):
        count = len(namelist)
        for i in range(count):
            name = namelist[i]
            if self.PlayList.GetList().count(urllist[i]) <= 0:
                self.addToPlayList(name,urllist[i],dur[i])

        if self.table.isHidden():
            self.Btntable.clicked()
        else:
            self.setAutoLayout()


    def setMiddleStackWidget0(self,p):
        self.midleft0 = p
    def setShowButtonName(self,strListName="新建列表"):
        self.Btntable.setListName(strListName)
    def setCurrentSongDuration(self,dur):
        self.table.PlayingWid.labDuration.setText(dur)
    def setPlayMode(self,mode):
        self.PlayList.setPlayMode(mode)

    def getPlayingWidget(self):
        return self.table.PlayingWid
    def currentAuthor(self):
        return self.table.PlayingWid.btnAuthor.text().simplified()
    def currentMusicName(self):
        return self.table.PlayingWid.songName()
    def updateCount(self):
        self.Btntable.slot_updateSongCount()
    def mediaList(self):
        return self.PlayList
    def getIndexByUrl(self,url):
        self.PlayList.GetList().indexOf(url)

    def getUrlByIndex(self,index):
        self.PlayList.GetList()[index]
    def isContainUrl(self,url):
        count = self.PlayList.GetList().count(url)
        if count <=0:
            return False
        else:
            return True
    def getHashByUrl(self,url):
        return self.PlayList.GetHashMap()[url]












